home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: howland.reston.ans.net!psinntp!psinntp!psinntp!psinntp!wmi2!joel
- From: joel@wmi.com (Joel Coltoff)
- Subject: Re: Fastest way to computer log(base2) of x?
- Message-ID: <1996Feb7.205235.29897@wmi.com>
- Organization: Woodward McCoach, Inc.
- References: <4f647p$lc5@druid.borland.com> <9602061633.AA15316@dxmint.cern.ch> <4f8rtu$1ib@fountain.mindlink.net>
- Date: Wed, 7 Feb 1996 20:52:35 GMT
-
-
- In a project I worked on a LONG time ago we solved this in a
- clever way. We had the one advantage that there was an upper
- bound on x. We needed to find y such that 2**y >= x for values
- of x <= 65535 ( i.e y <= 16).
-
- The approach we took was a binary search using the "? :" construct.
- It works out to a few simple compares and no shifts, multiplies, etc.
-
- I don't have it at hand and can't be bothered to reconstruct it. It
- shouldn't take long for you to do. The general scheme was (I don't
- claim that this form of it is right)
-
- y = x < 512 ?
- ( x < 32 ?
- ( x < 8 ?
- ( x < 4 ? ( x < 2 ? : 1 ) : 2 ) : 3 )) : x < 128 ? :
- ^ ^ ^
- | | |
- values for y -------------------------------------
-
- Yes it's an unreadable mess but it is fast. For more fun take the parens
- out after you've got it working.
-